#include<vector>
#include<unordered_map>
using std::unordered_map;
using std::vector;


class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        if (n == 0) return tasks.size();
        int maxFreq = 0, maxCount = 0, total = tasks.size();
        unordered_map<char, int> mp;
        for (auto &ch: tasks) {
            if (mp.find(ch) == mp.end()) mp[ch] = 1;
            else mp[ch]++;
            maxCount = maxCount < mp[ch] ? mp[ch] : maxCount;
            
        }
        for (auto &vals: mp) {
            if (vals.second == maxCount) maxFreq++;
        }

        int num = (maxCount-1) * (n+1) + maxFreq;
        num = (num < total) ? total : num;
        return num;
    }
};